package com.mystudy.jcu.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * TODO:  {@link Semaphore}
 * 1.可以同时获取多个信号量
 * 2.acquireUninterruptibly 不可被中断的获取
 * 3.drainPermits 获取所有的许可证
 * @author acy
 * @since 2019/06/19 15:13
 */
public class SemaphoreTest2 {
	//定义一个连接池
	public static void main(String[] args) throws InterruptedException {
		Semaphore semaphore = new Semaphore(2);
		for (int i = 0; i < 2; i++) {
			new Thread(()->{
				System.out.println(Thread.currentThread().getName() + "in");
				try {
					semaphore.acquire(1);
					System.out.println(Thread.currentThread().getName() + "get semaphore");
					TimeUnit.SECONDS.sleep(2);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}finally {
					semaphore.release(1);
				}
				System.out.println(Thread.currentThread().getName() + "out");
			}).start();
		}
		while (true){
			System.out.println("available semaphore"+semaphore.availablePermits());
			System.out.println("wait for semaphore thread number"+semaphore.getQueueLength());
			TimeUnit.SECONDS.sleep(1);
		}
	}
}
